//
//  RefreshControl.swift
//  新浪微博
//
//  Created by 李赛 on 15/5/22.
//  Copyright (c) 2015年 李赛. All rights reserved.
//

import UIKit

class RefreshControl: UIRefreshControl {

    // 使用xib的时候调用
    override func awakeFromNib() {
        println(__FUNCTION__)
        prepareView()
    }
    
    // 纯代码开发的时候调用
    override init() {
        super.init()
        println(__FUNCTION__)
        prepareView()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        println(__FUNCTION__)
    }
    
    // 准备子视图
    var refreshView : RefreshView?
    
    private func prepareView(){
        // 加载xib
        let r = NSBundle.mainBundle().loadNibNamed("RefreshView", owner: nil, options: nil).last as! RefreshView
        self.addSubview(r)
        
        // 设置约束
        r.setTranslatesAutoresizingMaskIntoConstraints(false)
        var cons = [AnyObject]()
        
        // 添加约束
        cons += NSLayoutConstraint.constraintsWithVisualFormat("H:[r(136)]", options: NSLayoutFormatOptions.AlignAllCenterX, metrics: nil, views: ["r":r])
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[r(60)]", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: ["r":r])
        
        cons.append(NSLayoutConstraint(item: r, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        
        self.addConstraints(cons)
        
        self.refreshView = r
        
        // 用KVO监听frame的变化
        self.addObserver(self, forKeyPath: "frame", options: NSKeyValueObservingOptions.New, context: nil)
    }
    
    // 释放
    deinit {
        self.removeObserver(self, forKeyPath: "frame")
    }
    
    // 显示提示标记
    var showTipFlag = false
    
    // 是否正在加载
    var isLoading = false
    
    //
    override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
        if self.frame.origin.y > 0 {
            return
        }
        
        // 判断是否刷新
        if refreshing && !isLoading {
            // 播放动画 
            refreshView?.startLoading()
            // 设置标记
            isLoading = true
            //  返回
            return
        }
        
        // 更改提示内容
        if self.frame.origin.y < -150 {
            refreshView?.tipText.text = "松开刷新......"
            println(",./")
        }
        // 判断箭头指向
        if self.frame.origin.y < -50 && !showTipFlag {
            showTipFlag = true
            refreshView?.rotateTipIcon(showTipFlag)
            refreshView?.tipText.text = "下拉刷新......"
            
        }else if self.frame.origin.y > -50 && showTipFlag {
            showTipFlag = false
            refreshView?.rotateTipIcon(showTipFlag)
            
        }
    }
    
    // 结束刷新
    override func endRefreshing() {
        super.endRefreshing()
        
        // 停止动画
        refreshView?.stopLoading()
        // 重新设置刷新标记
        isLoading = false
    }
    
}

class RefreshView: UIView {
    
    // 箭头图标
    @IBOutlet weak var tipIcon: UIImageView!
    
    // 加载图标
    @IBOutlet weak var loadingIcon: UIImageView!
    
    // 提示视图
    @IBOutlet weak var tipView: UIView!
    
    // 提示内容
    @IBOutlet weak var tipText: UILabel!
    
    private func rotateTipIcon(clockWise : Bool) {
        var angle = CGFloat(M_PI)
        angle += clockWise ? 0.01 : -0.01
        
        UIView.animateWithDuration(0.5, animations: { () -> Void in
            self.tipIcon.transform = CGAffineTransformRotate(self.tipIcon.transform, angle)
        })
    }
    
    // 播放旋转动画
    func startLoading(){
        tipView.hidden = true
        
        let anima = CABasicAnimation(keyPath: "transform.rotation")
        anima.toValue = 2 * M_PI
        anima.repeatCount = MAXFLOAT
        // 动画执行一次的时间
        anima.duration = 0.5
        
        loadingIcon.layer.addAnimation(anima, forKey: nil)
    }
    
    // 停止动画
    func stopLoading() {
        loadingIcon.layer.removeAllAnimations()
        
        tipView.hidden = false
    }
    
}
